import axios from 'axios'
import {userStore} from '@/stores/user'

// 设置服务器根地址

export const baseURL = 'http://127.0.0.1:5173/'

// 创建axios实例
const instance = axios.create({
    baseURL,
    timeout: 3000,
})

/* 
    请求拦截器
    + 判断是否有token，有的话把token放到请求头的 Authorization 字段里面
*/
instance.interceptors.request.use(
    config => {

        let count = userStore()
        let token = count.getToken
        if(token){
            config.headers['Authorization'] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

/* 
    响应拦截器
*/
instance.interceptors.response.use(
    response => {
        return response.data
    },
    error => {
        const { response } = error
        if (response) {
            const status = response.status
            switch (status) {
                case 401:
                    break
                case 402:
                    break
                case 403:
                    break
                case 404:
                    break
                default:
                    break
            }
        } else {
            if (!window.navigator.onLine) {
                // 网络崩了
                return
            } else {
                // 连接服务器出错
                return Promise.reject(error)
            }
        }
        return Promise.reject(error)
    }
)
export default instance
